package com.buaa.divinationmaster.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.buaa.divinationmaster.R;
import com.buaa.divinationmaster.model.DivinationRecord;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 历史记录适配器
 */
public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder> {
    
    private Context context;
    private List<DivinationRecord> records;
    private SimpleDateFormat dateFormat;
    
    public HistoryAdapter(Context context, List<DivinationRecord> records) {
        this.context = context;
        this.records = records;
        this.dateFormat = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
    }
    
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_history_record, parent, false);
        return new ViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        DivinationRecord record = records.get(position);
        
        // 设置图标
        holder.tvIcon.setText(record.getTypeIcon());
        
        // 设置类型
        holder.tvType.setText(record.getTypeDisplayName());
        
        // 设置时间
        String timeText = getRelativeTimeString(record.getTimestamp());
        holder.tvTime.setText(timeText);
        
        // 设置问题
        holder.tvQuestion.setText(record.getQuestion());
        
        // 设置简要结果（从解读文本中提取前50个字符）
        String summary = extractSummary(record.getInterpretation());
        holder.tvSummary.setText(summary);
        
        // 设置收藏状态
        holder.tvFavorite.setVisibility(record.isFavorite() ? View.VISIBLE : View.GONE);
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            showRecordDetailDialog(record);
        });
    }
    
    @Override
    public int getItemCount() {
        return records.size();
    }
    
    /**
     * 更新记录列表
     */
    public void updateRecords(List<DivinationRecord> newRecords) {
        this.records = newRecords;
        notifyDataSetChanged();
    }
    
    /**
     * 获取相对时间字符串
     */
    private String getRelativeTimeString(long timestamp) {
        long now = System.currentTimeMillis();
        long diff = now - timestamp;
        
        if (diff < 60 * 1000) { // 1分钟内
            return "刚刚";
        } else if (diff < 60 * 60 * 1000) { // 1小时内
            return (diff / (60 * 1000)) + "分钟前";
        } else if (diff < 24 * 60 * 60 * 1000) { // 24小时内
            return (diff / (60 * 60 * 1000)) + "小时前";
        } else if (diff < 7 * 24 * 60 * 60 * 1000) { // 7天内
            return (diff / (24 * 60 * 60 * 1000)) + "天前";
        } else {
            return dateFormat.format(new Date(timestamp));
        }
    }
    
    /**
     * 从解读文本中提取摘要
     */
    private String extractSummary(String interpretation) {
        if (interpretation == null || interpretation.isEmpty()) {
            return "暂无解读";
        }
        
        // 去除格式标记
        String clean = interpretation.replaceAll("【.*?】", "").replaceAll("\n", " ").trim();
        
        // 提取前50个字符
        if (clean.length() > 50) {
            return clean.substring(0, 50) + "...";
        } else {
            return clean;
        }
    }
    
    /**
     * 显示记录详情对话框
     */
    private void showRecordDetailDialog(DivinationRecord record) {
        StringBuilder details = new StringBuilder();
        details.append("【").append(record.getTypeDisplayName()).append("】\n\n");
        details.append("占卜时间：").append(dateFormat.format(new Date(record.getTimestamp()))).append("\n");
        details.append("问题：").append(record.getQuestion()).append("\n\n");
        details.append("详细解读：\n").append(record.getInterpretation());
        
        if (record.isFavorite()) {
            details.append("\n\n⭐ 已收藏");
        }
        
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
        builder.setTitle("占卜记录详情")
               .setMessage(details.toString())
               .setPositiveButton("确定", null)
               .setNegativeButton("分享", (dialog, which) -> {
                   shareRecord(record, details.toString());
               })
               .show();
    }
    
    /**
     * 分享占卜记录
     */
    private void shareRecord(DivinationRecord record, String details) {
        android.content.Intent shareIntent = new android.content.Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, details + "\n—— 来自占卜大师APP");
        shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "我的" + record.getTypeDisplayName() + "结果");
        
        context.startActivity(android.content.Intent.createChooser(shareIntent, "分享占卜记录"));
    }
    
    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvIcon, tvType, tvTime, tvQuestion, tvSummary, tvFavorite;
        
        ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvIcon = itemView.findViewById(R.id.tvIcon);
            tvType = itemView.findViewById(R.id.tvType);
            tvTime = itemView.findViewById(R.id.tvTime);
            tvQuestion = itemView.findViewById(R.id.tvQuestion);
            tvSummary = itemView.findViewById(R.id.tvSummary);
            tvFavorite = itemView.findViewById(R.id.tvFavorite);
        }
    }
}
